package com.hirain.fbg.mail;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.StringWriter;

/**
 * Created by caicf on 2016/7/23.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-mail.xml")
public class Email {

    @Autowired
    private JavaMailSenderImpl javaMailSender;

    @Autowired
    private SimpleMailMessage simpleMailMessage;

    @Autowired
    private EmailUtil emailUtil;

    @Test
    public void test() {
//        simpleMailMessage.setFrom("cai_cf@126.com");
        simpleMailMessage.setTo("547461296@qq.com");
        simpleMailMessage.setSubject("说明书");
        simpleMailMessage.setText("hello world test");
        javaMailSender.send(simpleMailMessage);
    }

    @Test
    public void emailUtilTest() {
        emailUtil.send("547461296@qq.com","等等对对对","hello world");
    }


    @Autowired
    private VelocityEngine velocityEngine;

    @Test
    public void test2() throws MessagingException {
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg, true);
        helper.setFrom("cai_cf@126.com");
        helper.setTo("547461296@qq.com");
        helper.setSubject("这是一个测试说明");

        Template template=velocityEngine.getTemplate("index.vm");
        VelocityContext context=new VelocityContext();
        context.put("user", "MZULE");
        context.put("content", "Hello");

        StringWriter stringWriter=new StringWriter();
        template.merge(context,stringWriter);

        helper.setText(stringWriter.toString());
        javaMailSender.send(msg);
    }
}
